package edu.whu.assignment8.controller;

import edu.whu.assignment8.entity.Goods;
import edu.whu.assignment8.exception.GoodsAdminException;
import edu.whu.assignment8.impl.GoodsServiceImpl;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    GoodsServiceImpl goodsService;

    @GetMapping("/{id}")
    public ResponseEntity<Goods> getGoods(@ApiParam("商品Id")@PathVariable long id){
        Goods result = goodsService.getGoods(id);
        if(result==null) {
            return ResponseEntity.noContent().build();
        }else{
            return ResponseEntity.ok(result);
        }
    }

    @GetMapping("")
    public Page<Goods> findProduct(String name,
                                   Float price,
                                   Float stockQuantity,
                                   String category,
                                   String productType,
                                   String supplierName,
                                   @RequestParam(defaultValue = "0")Integer pageNum,
                                   @RequestParam(defaultValue = "10")Integer pageSize){
        Map<String,Object> condition=new HashMap<>();
        if(name!=null) {
            condition.put("name","%"+name+"%");
        }
        if(price!=null) {
            condition.put("price",price);
        }
        if(category!=null) {
            condition.put("category",category);
        }
        if(stockQuantity!=null) {
            condition.put("stockQuantity",stockQuantity);
        }
        if(productType!=null) {
            condition.put("goodsType",productType);
        }
        if(supplierName!=null) {
            condition.put("supplierName",supplierName);
        }
        return goodsService.findGoods(condition, PageRequest.of(pageNum,pageSize, Sort.by("id")));
    }


    @PostMapping("")
    @PreAuthorize("hasAuthority('goods/update')")
    public Goods addProduct(@RequestBody Goods goods) throws GoodsAdminException {
       return goodsService.addGoods(goods);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('goods/update')")
    public void updateProduct(@PathVariable long id,@RequestBody Goods goods) throws GoodsAdminException {
        goodsService.updateGoods(id, goods);
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('goods/update')")
    public void deleteProduct(@PathVariable long id){
        goodsService.deleteGoods(id);
    }

}
